<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 8.1.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Noto Serif SC:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"fjqz177.top","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="在网上找了半天都没有找到用Rust实现RSA算法的文章，没办法，只好自己对着自己用Python写的版本重写一遍😁。">
<meta property="og:type" content="article">
<meta property="og:title" content="用Rust实现RSA加密解密">
<meta property="og:url" content="https://fjqz177.top/posts/8/index.html">
<meta property="og:site_name" content="fjqz177的Hexo博客">
<meta property="og:description" content="在网上找了半天都没有找到用Rust实现RSA算法的文章，没办法，只好自己对着自己用Python写的版本重写一遍😁。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-12-04T10:33:00.000Z">
<meta property="article:modified_time" content="2025-11-03T10:29:11.094Z">
<meta property="article:author" content="fjqz177">
<meta property="article:tag" content="Rust">
<meta property="article:tag" content="密码学">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://fjqz177.top/posts/8/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>用Rust实现RSA加密解密 | fjqz177的Hexo博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<style>mjx-container[jax="SVG"] {
  direction: ltr;
}

mjx-container[jax="SVG"] > svg {
  overflow: visible;
}

mjx-container[jax="SVG"][display="true"] {
  display: block;
  text-align: center;
  margin: 1em 0;
}

mjx-container[jax="SVG"][justify="left"] {
  text-align: left;
}

mjx-container[jax="SVG"][justify="right"] {
  text-align: right;
}

g[data-mml-node="merror"] > g {
  fill: red;
  stroke: red;
}

g[data-mml-node="merror"] > rect[data-background] {
  fill: yellow;
  stroke: none;
}

g[data-mml-node="mtable"] > line[data-line] {
  stroke-width: 70px;
  fill: none;
}

g[data-mml-node="mtable"] > rect[data-frame] {
  stroke-width: 70px;
  fill: none;
}

g[data-mml-node="mtable"] > .mjx-dashed {
  stroke-dasharray: 140;
}

g[data-mml-node="mtable"] > .mjx-dotted {
  stroke-linecap: round;
  stroke-dasharray: 0,140;
}

g[data-mml-node="mtable"] > svg {
  overflow: visible;
}

[jax="SVG"] mjx-tool {
  display: inline-block;
  position: relative;
  width: 0;
  height: 0;
}

[jax="SVG"] mjx-tool > mjx-tip {
  position: absolute;
  top: 0;
  left: 0;
}

mjx-tool > mjx-tip {
  display: inline-block;
  padding: .2em;
  border: 1px solid #888;
  font-size: 70%;
  background-color: #F8F8F8;
  color: black;
  box-shadow: 2px 2px 5px #AAAAAA;
}

g[data-mml-node="maction"][data-toggle] {
  cursor: pointer;
}

mjx-status {
  display: block;
  position: fixed;
  left: 1em;
  bottom: 1em;
  min-width: 25%;
  padding: .2em .4em;
  border: 1px solid #888;
  font-size: 90%;
  background-color: #F8F8F8;
  color: black;
}

foreignObject[data-mjx-xml] {
  font-family: initial;
  line-height: normal;
  overflow: visible;
}

.MathJax path {
  stroke-width: 3;
}

mjx-container[display="true"] {
  overflow: auto hidden;
}

mjx-container[display="true"] + br {
  display: none;
}
</style><link rel="alternate" href="/atom.xml" title="fjqz177的Hexo博客" type="application/rss+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>
    <a target="_blank" rel="noopener" href="https://github.com/fjqz177" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#000000; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">fjqz177的Hexo博客</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://fjqz177.top/posts/8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/my_avatar.jpg">
      <meta itemprop="name" content="fjqz177">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          用Rust实现RSA加密解密
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2023-12-04 18:33:00" itemprop="dateCreated datePublished" datetime="2023-12-04T18:33:00+08:00">2023-12-04</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2025-11-03 18:29:11" itemprop="dateModified" datetime="2025-11-03T18:29:11+08:00">2025-11-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E7%BC%96%E7%A8%8B/" itemprop="url" rel="index"><span itemprop="name">编程</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/posts/8/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/posts/8/" itemprop="commentCount"></span>
    </a>
  </span>
  
  <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>4k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>4 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="在网上找了半天都没有找到用rust实现rsa算法的文章没办法只好自己对着自己用python写的版本重写一遍">在网上找了半天都没有找到用<code>Rust</code>实现<code>RSA</code>算法的文章，没办法，只好自己对着自己用<code>Python</code>写的版本重写一遍😁。</h1>
<span id="more"></span>
<h1 id="这是源代码">这是源代码</h1>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">use</span> num_bigint::BigInt; <span class="comment">//用于超大整数的计算</span></span><br><span class="line"><span class="keyword">use</span> num_traits::{One, Zero}; <span class="comment">//用于BigInt的常量0和1</span></span><br><span class="line"><span class="keyword">use</span> std::time::Instant; <span class="comment">//用于计算程序运行时间</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 扩展欧几里得算法</span></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">ext_gcd</span>(a: &amp;BigInt, b: &amp;BigInt) <span class="punctuation">-&gt;</span> (BigInt, BigInt, BigInt) {</span><br><span class="line">    <span class="keyword">if</span> *b == Zero::<span class="title function_ invoke__">zero</span>() {</span><br><span class="line">        (a.<span class="title function_ invoke__">clone</span>(), One::<span class="title function_ invoke__">one</span>(), Zero::<span class="title function_ invoke__">zero</span>())</span><br><span class="line">    } <span class="keyword">else</span> {</span><br><span class="line">        <span class="keyword">let</span> (r, x1, y1) = <span class="title function_ invoke__">ext_gcd</span>(b, &amp;(a % b));</span><br><span class="line">        <span class="keyword">let</span> <span class="variable">x</span> = y1.<span class="title function_ invoke__">clone</span>();</span><br><span class="line">        <span class="keyword">let</span> <span class="variable">y</span> = x1 - ((a / b) * &amp;y1);</span><br><span class="line">        (r, x, y)</span><br><span class="line">    }</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">// 超大整数超大次幂再对超大的整数取模</span></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">exp_mode</span>(base: &amp;BigInt, exponent: &amp;BigInt, modulus: &amp;BigInt) <span class="punctuation">-&gt;</span> BigInt {</span><br><span class="line">    <span class="keyword">let</span> <span class="variable">zero</span> = Zero::<span class="title function_ invoke__">zero</span>();</span><br><span class="line">    <span class="keyword">let</span> <span class="variable">one</span>: BigInt = One::<span class="title function_ invoke__">one</span>();</span><br><span class="line">    <span class="keyword">let</span> <span class="variable">two</span> = &amp;one + &amp;one;</span><br><span class="line">    <span class="keyword">let</span> <span class="keyword">mut </span><span class="variable">result</span> = one.<span class="title function_ invoke__">clone</span>();</span><br><span class="line">    <span class="keyword">let</span> <span class="keyword">mut </span><span class="variable">base</span> = base % modulus;</span><br><span class="line">    <span class="keyword">let</span> <span class="keyword">mut </span><span class="variable">exponent</span> = exponent.<span class="title function_ invoke__">clone</span>();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">while</span> exponent &gt; zero {</span><br><span class="line">        <span class="keyword">if</span> &amp;exponent % &amp;two == one {</span><br><span class="line">            result = result * &amp;base % modulus;</span><br><span class="line">        }</span><br><span class="line">        exponent = exponent &gt;&gt; <span class="number">1</span>;</span><br><span class="line">        base = &amp;base * &amp;base % modulus;</span><br><span class="line">    }</span><br><span class="line">    result</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">// 计算公钥和私钥</span></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">gen_key</span>(p: &amp;BigInt, q: &amp;BigInt) <span class="punctuation">-&gt;</span> ((BigInt, BigInt), (BigInt, BigInt)) {</span><br><span class="line">    <span class="keyword">let</span> <span class="variable">n</span> = p * q;</span><br><span class="line">    <span class="keyword">let</span> <span class="variable">fy</span> = (p - <span class="number">1u32</span>) * (q - <span class="number">1u32</span>);</span><br><span class="line">    <span class="keyword">let</span> <span class="variable">e</span>: BigInt = <span class="number">65537u32</span>.<span class="title function_ invoke__">into</span>();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">let</span> (_, x, _) = <span class="title function_ invoke__">ext_gcd</span>(&amp;e, &amp;fy);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">let</span> <span class="variable">d</span> = <span class="keyword">if</span> x &lt; Zero::<span class="title function_ invoke__">zero</span>() { x + &amp;fy } <span class="keyword">else</span> { x };</span><br><span class="line"></span><br><span class="line">    ((n.<span class="title function_ invoke__">clone</span>(), e), (n, d))</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">// 加密函数</span></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">encrypt</span>(m: &amp;BigInt, pubkey: &amp;(BigInt, BigInt)) <span class="punctuation">-&gt;</span> (BigInt, <span class="type">f64</span>) {</span><br><span class="line">    <span class="keyword">let</span> <span class="variable">start_time</span> = Instant::<span class="title function_ invoke__">now</span>();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">let</span> <span class="variable">c</span> = <span class="title function_ invoke__">exp_mode</span>(m, &amp;pubkey.<span class="number">1</span>, &amp;pubkey.<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">let</span> <span class="variable">time_elapsed</span> = start_time.<span class="title function_ invoke__">elapsed</span>().<span class="title function_ invoke__">as_secs_f64</span>();</span><br><span class="line"></span><br><span class="line">    (c, time_elapsed)</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">// 解密函数</span></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">decrypt</span>(c: &amp;BigInt, selfkey: &amp;(BigInt, BigInt)) <span class="punctuation">-&gt;</span> (BigInt, <span class="type">f64</span>) {</span><br><span class="line">    <span class="keyword">let</span> <span class="variable">start_time</span> = Instant::<span class="title function_ invoke__">now</span>();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">let</span> <span class="variable">m</span> = <span class="title function_ invoke__">exp_mode</span>(c, &amp;selfkey.<span class="number">1</span>, &amp;selfkey.<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">let</span> <span class="variable">time_elapsed</span> = start_time.<span class="title function_ invoke__">elapsed</span>().<span class="title function_ invoke__">as_secs_f64</span>();</span><br><span class="line"></span><br><span class="line">    (m, time_elapsed)</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="comment">// 判断字符串是否为纯数字</span></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">is_str_numeric</span>(s: &amp;<span class="type">str</span>) <span class="punctuation">-&gt;</span> <span class="type">bool</span> {</span><br><span class="line">    <span class="keyword">let</span> <span class="variable">re</span> = regex::Regex::<span class="title function_ invoke__">new</span>(<span class="string">r"^\d+$"</span>).<span class="title function_ invoke__">unwrap</span>();</span><br><span class="line">    re.<span class="title function_ invoke__">is_match</span>(s)</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">main</span>() {</span><br><span class="line">    <span class="comment">// 此处应使用实际的用户输入，注意需要处理错误和异常的输入</span></span><br><span class="line">    <span class="keyword">let</span> <span class="variable">p</span> = <span class="string">"106697219132480173106064317148705638676529121742557567770857687729397446898790451577487723991083173010242416863238099716044775658681981821407922722052778958942891831033512463262741053961681512908218003840408526915629689432111480588966800949428079015682624591636010678691927285321708935076221951173426894836169"</span>.parse::&lt;BigInt&gt;().<span class="title function_ invoke__">unwrap</span>();</span><br><span class="line">    <span class="keyword">let</span> <span class="variable">q</span> = <span class="string">"144819424465842307806353672547344125290716753535239658417883828941232509622838692761917211806963011168822281666033695157426515864265527046213326145174398018859056439431422867957079149967592078894410082695714160599647180947207504108618794637872261572262805565517756922288320779308895819726074229154002310375209"</span>.parse::&lt;BigInt&gt;().<span class="title function_ invoke__">unwrap</span>();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 生成公钥和私钥</span></span><br><span class="line">    <span class="keyword">let</span> (pubkey, selfkey) = <span class="title function_ invoke__">gen_key</span>(&amp;p, &amp;q);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">loop</span> {</span><br><span class="line">        <span class="comment">// 此处应使用实际的用户输入，注意需要处理错误和异常的输入</span></span><br><span class="line">        <span class="built_in">println!</span>(<span class="string">"请输入要加密或解密的数字:"</span>);</span><br><span class="line">        <span class="keyword">let</span> <span class="keyword">mut </span><span class="variable">input</span> = <span class="type">String</span>::<span class="title function_ invoke__">new</span>();</span><br><span class="line">        std::io::<span class="title function_ invoke__">stdin</span>().<span class="title function_ invoke__">read_line</span>(&amp;<span class="keyword">mut</span> input).<span class="title function_ invoke__">unwrap</span>();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 判断输入是否为纯数字</span></span><br><span class="line">        <span class="keyword">if</span> <span class="title function_ invoke__">is_str_numeric</span>(&amp;input.<span class="title function_ invoke__">trim</span>()) {</span><br><span class="line">            <span class="comment">// 输入是纯数字</span></span><br><span class="line">            <span class="comment">// 将输入转换为BigInt类型</span></span><br><span class="line">            <span class="keyword">let</span> <span class="variable">message</span> = input.<span class="title function_ invoke__">trim</span>().parse::&lt;BigInt&gt;().<span class="title function_ invoke__">unwrap</span>();</span><br><span class="line">            <span class="built_in">println!</span>(<span class="string">"请输入要执行的操作(1为加密,2为解密,3为退出):"</span>);</span><br><span class="line">            <span class="keyword">let</span> <span class="keyword">mut </span><span class="variable">op</span> = <span class="type">String</span>::<span class="title function_ invoke__">new</span>();</span><br><span class="line">            std::io::<span class="title function_ invoke__">stdin</span>().<span class="title function_ invoke__">read_line</span>(&amp;<span class="keyword">mut</span> op).<span class="title function_ invoke__">unwrap</span>();</span><br><span class="line">            <span class="keyword">let</span> <span class="variable">op</span> = op.<span class="title function_ invoke__">trim</span>().parse::&lt;<span class="type">u32</span>&gt;().<span class="title function_ invoke__">unwrap</span>();</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 根据用户输入执行相应操作</span></span><br><span class="line">            <span class="keyword">match</span> op {</span><br><span class="line">                <span class="number">1</span> =&gt; {</span><br><span class="line">                    <span class="built_in">println!</span>(<span class="string">"待加密数字: {}"</span>, message);</span><br><span class="line">                    <span class="keyword">let</span> (c, d) = <span class="title function_ invoke__">encrypt</span>(&amp;message, &amp;pubkey);</span><br><span class="line">                    <span class="built_in">println!</span>(<span class="string">"加密结果: {}"</span>, c);</span><br><span class="line">                    <span class="built_in">println!</span>(<span class="string">"加密耗时: {:?}秒"</span>, d);</span><br><span class="line">                    ()</span><br><span class="line">                }</span><br><span class="line">                <span class="number">2</span> =&gt; {</span><br><span class="line">                    <span class="keyword">let</span> (m, d) = <span class="title function_ invoke__">decrypt</span>(&amp;message, &amp;selfkey);</span><br><span class="line">                    <span class="built_in">println!</span>(<span class="string">"解密结果: {}"</span>, m);</span><br><span class="line">                    <span class="built_in">println!</span>(<span class="string">"解密耗时: {:?}秒"</span>, d);</span><br><span class="line">                    ()</span><br><span class="line">                }</span><br><span class="line">                <span class="number">3</span> =&gt; {</span><br><span class="line">                    <span class="built_in">println!</span>(<span class="string">"退出程序"</span>);</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                }</span><br><span class="line">                _ =&gt; {</span><br><span class="line">                    <span class="built_in">println!</span>(<span class="string">"无效操作"</span>);</span><br><span class="line">                    <span class="keyword">continue</span>;</span><br><span class="line">                }</span><br><span class="line">            };</span><br><span class="line">        } <span class="keyword">else</span> {</span><br><span class="line">            <span class="comment">// 输入不是纯数字</span></span><br><span class="line">            <span class="built_in">println!</span>(<span class="string">"密码必须是纯数字！"</span>);</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        }</span><br><span class="line">    }</span><br><span class="line">}</span><br></pre></td></tr></table></figure>
<h1 id="这是toml文件">这是<code>Toml</code>文件</h1>
<figure class="highlight toml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="section">[dependencies]</span></span><br><span class="line"><span class="attr">num-bigint</span> = <span class="string">"0.4.4"</span></span><br><span class="line"><span class="attr">num-traits</span> = <span class="string">"0.2.17"</span></span><br><span class="line"><span class="attr">regex</span> = <span class="string">"1.10.2"</span></span><br></pre></td></tr></table></figure>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E5%AF%86%E7%A0%81%E5%AD%A6/" rel="tag"><i class="fa fa-tag"></i></a>
              <a href="/tags/Rust/" rel="tag"><i class="fa fa-tag"></i></a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/posts/7/" rel="prev" title="终极Github个人主页美化教程">
      <i class="fa fa-chevron-left"></i> 终极Github个人主页美化教程
    </a></div>
      <div class="post-nav-item">
    <a href="/posts/9/" rel="next" title="安装完fedora 39后要做的事">
      安装完fedora 39后要做的事 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%9C%A8%E7%BD%91%E4%B8%8A%E6%89%BE%E4%BA%86%E5%8D%8A%E5%A4%A9%E9%83%BD%E6%B2%A1%E6%9C%89%E6%89%BE%E5%88%B0%E7%94%A8rust%E5%AE%9E%E7%8E%B0rsa%E7%AE%97%E6%B3%95%E7%9A%84%E6%96%87%E7%AB%A0%E6%B2%A1%E5%8A%9E%E6%B3%95%E5%8F%AA%E5%A5%BD%E8%87%AA%E5%B7%B1%E5%AF%B9%E7%9D%80%E8%87%AA%E5%B7%B1%E7%94%A8python%E5%86%99%E7%9A%84%E7%89%88%E6%9C%AC%E9%87%8D%E5%86%99%E4%B8%80%E9%81%8D"><span class="nav-number">1.</span> <span class="nav-text">在网上找了半天都没有找到用Rust实现RSA算法的文章，没办法，只好自己对着自己用Python写的版本重写一遍😁。</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%BF%99%E6%98%AF%E6%BA%90%E4%BB%A3%E7%A0%81"><span class="nav-number">2.</span> <span class="nav-text">这是源代码</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%BF%99%E6%98%AFtoml%E6%96%87%E4%BB%B6"><span class="nav-number">3.</span> <span class="nav-text">这是Toml文件</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="fjqz177"
      src="/images/my_avatar.jpg">
  <p class="site-author-name" itemprop="name">fjqz177</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">11</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">3</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">12</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/fjqz177" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;fjqz177" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:fjqz177@139.com" title="E-Mail → mailto:fjqz177@139.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/u/5862441076" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;u&#x2F;5862441076" rel="noopener" target="_blank"><i class="fab fa-weibo fa-fw"></i>Weibo</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://space.bilibili.com/436591517" title="Bilibili → https:&#x2F;&#x2F;space.bilibili.com&#x2F;436591517" rel="noopener" target="_blank"><i class="iconfont icon-bilibili-line fa-fw"></i>Bilibili</a>
      </span>
      <span class="links-of-author-item">
        <a href="/atom.xml" title="RSS → &#x2F;atom.xml"><i class="fa fa-rss fa-fw"></i>RSS</a>
      </span>
  </div>


<!-- recent posts -->
      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2022 – 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">fjqz177</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">44k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">40 分钟</span>
</div><div>
  <span id="sitetime"></span>
  <script language=javascript>
      function siteTime(){
          window.setTimeout("siteTime()", 1000);
          var seconds = 1000;
          var minutes = seconds * 60;
          var hours = minutes * 60;
          var days = hours * 24;
          var years = days * 365;
          var today = new Date();
          var todayYear = today.getFullYear();
          var todayMonth = today.getMonth()+1;
          var todayDate = today.getDate();
          var todayHour = today.getHours();
          var todayMinute = today.getMinutes();
          var todaySecond = today.getSeconds();
          /* 
          Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
          year - 作为date对象的年份，为4位年份值
          month - 0-11之间的整数，做为date对象的月份
          day - 1-31之间的整数，做为date对象的天数
          hours - 0(午夜24点)-23之间的整数，做为date对象的小时数
          minutes - 0-59之间的整数，做为date对象的分钟数
          seconds - 0-59之间的整数，做为date对象的秒数
          microseconds - 0-999之间的整数，做为date对象的毫秒数
      */
          var t1 = Date.UTC(2021,12,23,11,40,00); //北京时间2018-2-13 00:00:00
          var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
          var diff = t2-t1;
      var diffYears = Math.floor(diff/years);
      var diffDays = Math.floor((diff/days)-diffYears*365);
      var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
      var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
      var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
      document.getElementById("sitetime").innerHTML=" 已运行"+/*diffYears+" 年 "+*/diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒";
    }
      siteTime();
  </script>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script color='0,0,0' opacity='0.8' zIndex='-1' count='100' src="/lib/canvas-nest/canvas-nest-nomobile.min.js"></script>
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'default',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'sOHn0nk7MNCH5aJPMaRsap68-gzGzoHsz',
      appKey     : '8cwjoCV2IhxqqlVyLdZ96lqe',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true}});</script></body>
</html>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>